package com.dbdata.move.dao;

import com.dbdata.move.PinYinTool;
import com.dbdata.move.model.UserBaseInfo;
import com.wksc.framework.dao.BaseDao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @author nibo
 */
@Repository
public class UserDao extends BaseDao {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserDao.class);

    @Autowired
    private DataSource dataSource;

    /**
     * 根据身份证号或护照号查询查询用户信息
     *
     * @param identityCard 身份证号或护照号
     * @return 用户信息
     */
    public List<UserBaseInfo> findUserByIdentityCard(String identityCard) {
        String hql = "FROM UserBaseInfo WHERE identityCard = ? OR passport = ?";
        return listHql(hql, identityCard, identityCard);
    }

    /**
     * 根据身份证号或护照号更新用户的组织机构
     *
     * @param identityCard 身份证号或护照号
     * @param organizeId   组织机构id
     */
    public void updateUserOrganize(String identityCard, long organizeId) {
        String sql = "UPDATE user_base_info t SET t.ORGANIZE = ? " +
                "WHERE t.IDENTITY_CARD = ? OR t.PASSPORT = ?";
        executeUpdate(sql, false, organizeId, identityCard, identityCard);

    }

    /**
     * 更新用户
     */
    public void updateUserPinYinSX() throws SQLException {
        // 这里直接使用JDBC批量操作，提高数据更新的速度

        Connection connection = dataSource.getConnection();
        String sql = "UPDATE user_base_info t SET t.PIN_YIN_SX = ? WHERE t.ID = ?";
        PreparedStatement stmt = connection.prepareStatement(sql);
        connection.setAutoCommit(false);
        String pinyinSX;
        LOGGER.debug("查询所有用户信息...");
        List<UserBaseInfo> listUser = findUserInfoAll();
        for (int i = 0; i < listUser.size(); i++) {
            pinyinSX = PinYinTool.getPinYinSX(listUser.get(i).getUserName());
            LOGGER.info("更新用户：{}(id:{})，的拼音简写为：{}",
                    listUser.get(i).getUserName(), listUser.get(i).getId(), pinyinSX);
            stmt.setString(1, pinyinSX);
            stmt.setLong(2, listUser.get(i).getId());
            stmt.addBatch();
            if (i % 200 == 0) {
                stmt.executeBatch();
                connection.commit();
            }
        }
        stmt.executeBatch();
        connection.commit();
    }

    /**
     * 查询所有的用户基础信息
     *
     * @return 用户信息列表
     */
    public List<UserBaseInfo> findUserInfoAll() {
        String hql = "FROM UserBaseInfo";
        return listHql(hql);
    }
}
